package com.igeek.ssm.controller;

import com.igeek.ssm.entity.User;
import com.igeek.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Description TODO
 * @Author chenmin
 * @Version 1.0
 * @Date 2023/2/9 15:51
 */
@Controller
public class IndexController {

    @Autowired
    private UserService userService;

    //显示成功界面
    @GetMapping("/success.html")
    public String success(Model model){
        //请求域中存放键值对
        model.addAttribute("msg" , "今天明天后天");
        model.addAttribute("link","http://www.baidu.com");
        //跳转 /templates/success.html页面
        return "success";
    }

    //显示登录界面
    @GetMapping({"/","/login.html"})
    public String gotoLogin(){
        //跳转 /templates/login.html页面
        return "login";
    }

    /**
     * HTML中表单input输入框，name属性必须与方法中形参名称一致；
     * HTML中表单input输入框，name属性必须与方法中形参pojo类型的属性名一致；
     */
    //处理登录请求的接口
    @PostMapping("/login")
    public String login(String name, String pwd, HttpSession session ,Model model){
        if(StringUtils.hasLength(name) && StringUtils.hasLength(pwd)){
            User user = userService.login(name , pwd);
            if(user!=null){
                //会话作用域存储登录成功者信息
                session.setAttribute("user",user);
                //跳转  /templates/main.html页面
                //"main"  forward请求转发，地址栏显示请求地址/login，一旦刷新地址栏，则会405 - Request method 'GET' not supported
                ///main   redirect响应重定向，地址栏显示目标地址/main
                return "redirect:/main";
            }
        }
        //请求作用域存储登录失败信息
        model.addAttribute("errorMsg","登录失败");
        //跳转 /templates/login.html页面
        return "login";
    }

    //显示main.html页面
    @GetMapping("/main")
    public String gotoMain(){
        //跳转 /templates/main.html页面
        return "main";
    }

    //登出
    @GetMapping("/logout")
    public String logout(HttpSession session,Model model){
        session.invalidate();
        //请求作用域存储登录失败信息
        model.addAttribute("errorMsg","已登出");
        //跳转 /templates/login.html页面
        return "login";
    }


}
